package com.quan.server.helper;

import com.mark.util.CommonUtil;
import com.mark.util.JsonUtil;
import com.quan.server.Const;
import com.quan.server.beans.ConfigItem;
import com.quan.server.beans.Customer;
import com.quan.server.beans.Income;
import com.quan.server.beans.InvitingRecord;
import com.quan.server.beans.TaobaoOrder;
import com.quan.server.helper.pay.WeChatSendRedPack;
import com.quan.server.jpa.ConfigItemRepository;
import com.quan.server.jpa.CustomerRepository;
import com.quan.server.jpa.IncomeRepository;
import com.quan.server.jpa.InvitingRecordRepository;
import com.quan.server.jpa.TaobaoOrderRepository;
import org.glassfish.jersey.internal.inject.Custom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

@Component
public class MyAppHelper {
    private static Logger logger = LoggerFactory.getLogger(MyAppHelper.class);
    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private InvitingRecordRepository invitingRecordRepository;

    @Autowired
    private IncomeRepository incomeRepository;

    @Autowired
    private ConfigItemRepository configItemRepository;

    @Autowired
    private TaobaoOrderRepository taobaoOrderRepository;

    @Autowired
    private AlimamaClient alimamaClient;

    public String handleMessageByOpenId(String weixinMPOpenId, String message) {
        logger.error("handleMessageByOpenId------------------->"+isYouhuiquanMessage(message));
        Customer customerSender = getIfCustomerByWeixinMPOpenId(weixinMPOpenId);
        logger.error("2------------>customerSender=" + JsonUtil.bean2Json(customerSender));
        if (isMessageQuan(message)) {
            logger.error("2.1------------>isMessageQuan");
            String senderAlimamaPid = customerSender.alimamaPid;
            String quan = alimamaClient.getQuan(message, senderAlimamaPid);
            return quan;
        }
        if (isMessageGetMoneyRest(message)) {
            logger.error("2.2------------>isMessageGetMoneyRest");
            Income incomeSender = getIfIncomeByCustomer(customerSender);
            String messageMoneyRest = getMessageMoneyRest(incomeSender.moneyTotal, incomeSender.moneyRest);
            return messageMoneyRest;
        }
        if (isMessageWithdrawMoney(message)) {
            logger.error("2.3------------>isMessageWithdrawMoney");
            Income incomeSender = getIfIncomeByCustomer(customerSender);
            String messageMoneyWithdraw = getMessageMoneyWithdraw(incomeSender.moneyTotal, incomeSender.moneyRest);
            return messageMoneyWithdraw;
        }
        logger.error("2.4------------>");
        return message;
    }

    public String handleMessage(String weixinIdSender, String message) {
        Customer customerSender = getIfCustomerByWeixinId(weixinIdSender);
        if (isMessageQuan(message)) {
            String senderAlimamaPid = customerSender.alimamaPid;
            String quan = alimamaClient.getQuan(message, senderAlimamaPid);
            return quan;
        }
        if (isMessageGetMoneyRest(message)) {
            Income incomeSender = getIfIncomeByCustomer(customerSender);
            String messageMoneyRest = getMessageMoneyRest(incomeSender.moneyTotal, incomeSender.moneyRest);
            return messageMoneyRest;
        }
        if (isMessageWithdrawMoney(message)) {
            Income incomeSender = getIfIncomeByCustomer(customerSender);
            String messageMoneyWithdraw = getMessageMoneyWithdraw(incomeSender.moneyTotal, incomeSender.moneyRest);
            return messageMoneyWithdraw;
        }
        return message;
    }

    public boolean isYouhuiquanMessage(String message) {
        boolean isMessageQuan = isMessageQuan(message);
        logger.error("a----------1:" + isMessageQuan);
        boolean isMessageGetMoneyRest = isMessageGetMoneyRest(message);
        logger.error("a----------2:" + isMessageGetMoneyRest);
        boolean isMessageWithdrawMoney = isMessageWithdrawMoney(message);
        logger.error("a----------3:" + isMessageGetMoneyRest);
        return isMessageQuan || isMessageGetMoneyRest || isMessageWithdrawMoney;
    }

    public Income getIfIncomeByCustomerId(String customerId) {
        Income income = incomeRepository.findIncomeByCustomerId(customerId);
        if (income == null) {
            income = new Income();
            income.id = CommonUtil.createRandomId();
            income.customerId = customerId;
            incomeRepository.save(income);
        }
        return income;
    }

    private Income getIfIncomeByCustomer(Customer customerSender) {
        String customerId = customerSender.id;
        Income income = getIfIncomeByCustomerId(customerId);
        return income;
    }

    public Customer getIfCustomerByWeixinMPOpenId(String weixinMPOpenId) {
        Customer customer = customerRepository.findCustomerByWeixinMPOpenId(weixinMPOpenId);
        if (customer == null) {
            customer = new Customer();
            customer.id = CommonUtil.createRandomId();
            customer.weixinMPOpenId = weixinMPOpenId;
            customer.alimamaPid = alimamaClient.createPid(customer.id);
            customer = customerRepository.save(customer);
        }
        return customer;
    }

    public Customer getIfCustomerByWeixinId(String weixinId) {
        Customer customer = customerRepository.findCustomerByWeixinId(weixinId);
        if (customer == null) {
            customer = new Customer();
            customer.id = CommonUtil.createRandomId();
            customer.weixinId = weixinId;
            customer.alimamaPid = alimamaClient.createPid(customer.id);
            customer = customerRepository.save(customer);
        }
        return customer;
    }

    public static boolean isMessageQuan(String message) {
        if (AlimamaClient.getTaoPasswordKey(message) != null) {
            return true;
        }
        return false;
    }

    public static boolean isMessageGetMoneyRest(String message) {
        if (message.trim().equals("余额")) {
            return true;
        }
        return false;
    }

    public static boolean isMessageWithdrawMoney(String message) {
        if (message.trim().equals("提现")) {
            return true;
        }
        return false;
    }

    public static List<String> getShareListByCustomerId(InvitingRecord invitingRecord) {
        List<String> inviterCustomerIdList = JsonUtil.string2List(invitingRecord.inviterCustomerIdList);
        return inviterCustomerIdList;
    }

    //如果customerId对应的邀请记录不存在，就创建
    public InvitingRecord getIfInvitingRecordByCustomerId(String customerId) {
        InvitingRecord invitingRecord = invitingRecordRepository.findOne(customerId);
        if (invitingRecord == null) {
            invitingRecord = new InvitingRecord();
            invitingRecord.id = customerId;
            invitingRecord.customerId = customerId;
            invitingRecord = InvitingRecord.addNewCustomerId(invitingRecord, customerId);
            invitingRecord = invitingRecordRepository.save(invitingRecord);
        }
        return invitingRecord;
    }

    public InvitingRecord getIfInvitingRecordByWeixinIdSenderAndWeixinIdReceiver(String weixinIdSender, String weixinIdReceiver) {
        Customer customerSender = getIfCustomerByWeixinId(weixinIdSender);
        Customer customerReceiver = getIfCustomerByWeixinId(weixinIdReceiver);
        InvitingRecord invitingRecord = getIfInvitingRecordBySenderCustomerIdAndReceiverCustomerId(customerSender.id, customerReceiver.id);
        return invitingRecord;
    }

    /**
     * 微信消息发送者 的 邀请关系 绑定为 微信消息的接受者 的 邀请关系
     *
     * @param senderCustomerId
     * @param receiverCustomerId
     */
    public InvitingRecord getIfInvitingRecordBySenderCustomerIdAndReceiverCustomerId(String senderCustomerId, String receiverCustomerId) {
        InvitingRecord senderInvitingRecord = getIfInvitingRecordByCustomerId(senderCustomerId);
        InvitingRecord receiverInvitingRecord = getIfInvitingRecordByCustomerId(receiverCustomerId);
        List<String> shareList = getShareListByCustomerId(receiverInvitingRecord);
        String shareListString = JsonUtil.list2String(shareList);
        senderInvitingRecord.inviterCustomerIdList = shareListString;
        senderInvitingRecord = InvitingRecord.addNewCustomerId(senderInvitingRecord, senderInvitingRecord.customerId);

        senderInvitingRecord = invitingRecordRepository.save(senderInvitingRecord);
        return senderInvitingRecord;
    }

    public static String getMessageMoneyRest(double moneyTotal, double moneyEnableWithdraw) {
        return String.format(Const.TemplateMoneyRest, moneyTotal, moneyEnableWithdraw);
    }

    public static String getMessageMoneyWithdraw(double moneyTotal, double moneyEnableWithdraw) {
        return String.format(Const.TemplateMoneyWithdraw, moneyTotal, moneyEnableWithdraw);
    }

    public Map getIncomeInfo(List<String> shareCustomerIdList, Map shareInfo) {
        return null;
    }

    public List<String> getShareCustomerIdListByCustomer(Customer customer) {
        String customerId = customer.id;
        InvitingRecord invitingRecord = getIfInvitingRecordByCustomerId(customerId);
        List<String> shareCustomerIdList = JsonUtil.json2Bean(invitingRecord.inviterCustomerIdList, List.class);
        return shareCustomerIdList;
    }

    public Customer getCustomerByTaobaoOrder(TaobaoOrder taobaoOrder) {
        String alimamaPid = taobaoOrder.alimamaPid;
        Customer customer = customerRepository.findCustomerByAlimamaPid(alimamaPid);
        return customer;
    }

//    public Map getShareInfo() {
//        return getShareConfiguration();
//    }

    public ConfigItem getIfPropertyByKey(String key) {
        ConfigItem configItem = configItemRepository.findConfigItemByName(key);
        if (configItem == null) {
            configItem = new ConfigItem();
            configItem.id = CommonUtil.createRandomId();
            configItem.name = key;
            configItem.value = "";
            configItem = configItemRepository.save(configItem);
        }
        return configItem;
    }

    public void setConfiguration(Map<String, String> configuration) {
        for (String key : configuration.keySet()) {
            String value = configuration.get(key);
            ConfigItem configItem = getIfPropertyByKey(key);
            configItem.value = value;
            configItemRepository.save(configItem);
        }
    }

    public Map<String, String> getConfiguration(List<String> keyList) {
        Map<String, String> configuration = new HashMap<>();
        for (String key : keyList) {
            ConfigItem configItem = getIfPropertyByKey(key);
            String value = configItem.value;
            configuration.put(key, value);
        }
        return configuration;
    }

    public void setDefaultTaobaoAccountConfiguration(Map<String, String> configuration) {
        setConfiguration(configuration);
    }

    public Map<String, String> getDefaultTaobaoAccountConfiguration() {
        List<String> keyList = new Vector<>();
        keyList.add(Const.KeyDefaultTaobaoAccountAppKey);
        keyList.add(Const.KeyDefaultTaobaoAccountAppSecret);
        Map<String, String> configuration = getConfiguration(keyList);
        return configuration;
    }

    public void setShareConfiguration(Map<String, String> configuration) {
        setConfiguration(configuration);
    }

    public Map<String, String> getShareConfiguration() {
        List<String> keyList = new Vector<>();
        keyList.add(Const.KeyShareA);
        keyList.add(Const.KeyShareB);
        keyList.add(Const.KeyShareC);
        Map<String, String> configuration = getConfiguration(keyList);
        return configuration;
    }

    public void importTaobaoOrder(TaobaoOrder taobaoOrder) {
        if (taobaoOrderRepository.findTaobaoOrderByOrderId(taobaoOrder.orderId) != null) {
            logger.error("taobaoOrder has been handled, orderId:" + taobaoOrder.orderId);
            return;
        }
        Customer customer = getCustomerByTaobaoOrder(taobaoOrder);
        List<String> shareCustomerIdList = getShareCustomerIdListByCustomer(customer);
        Map shareConfiguration = getShareConfiguration();
        double money = taobaoOrder.money;
        Map<String, Double> shareMoneyInfo = new HashMap<>();
        int size = shareCustomerIdList.size();
        for (int i = 0; i < size; i++) {
            String customerId = shareCustomerIdList.get(i);
            double shareMoney = money * 0.1 * (i + 1);//获取分配规则
            shareMoneyInfo.put(customerId, shareMoney);
        }

        int currentYear = CommonUtil.getYear();
        int currentMonth = CommonUtil.getMonth();
        int currentDay = CommonUtil.getDay();

        for (String customerId : shareMoneyInfo.keySet()) {
            Income income = getIfIncomeByCustomerId(customerId);
            double shareMoney = shareMoneyInfo.get(customerId);
            income = Income.updateIncome(income, currentYear, currentMonth, currentDay, shareMoney);
            incomeRepository.save(income);
        }
        taobaoOrder.id = CommonUtil.createRandomId();
        taobaoOrderRepository.save(taobaoOrder);
    }

    public Income getIncomeRequireWithdraw(String id, double money) {
        Income income = incomeRepository.findOne(id);
        income = Income.requireWithdrawMoney(income, money);
        income = incomeRepository.save(income);
        String weixinMPOpenId = getWeixinMPOpenIdByCustomerId(income.customerId);
        WeChatSendRedPack.sendRedPackage(weixinMPOpenId, (int) income.moneyFreeze * 100);

        income = Income.finishWithdrawMoney(income);
        income = incomeRepository.save(income);
        return income;
    }

    public String getWeixinMPOpenIdByCustomerId(String id) {
        Customer customer = customerRepository.findOne(id);
        return customer.weixinMPOpenId;
    }

    public Income getIncomeWithFinishWithdrawMoney(String id) {
        Income income = incomeRepository.findOne(id);
        if (income != null) {
            income = Income.finishWithdrawMoney(income);
            income = incomeRepository.save(income);
        }
        return income;
    }
}
